﻿/*
 * Copyright (C) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using UnityEngine;
using System.Collections;

public class EnemySpawner : MonoBehaviour {
    public GameObject[] Complexes; // set by editor
    public GameObject EnemyPrefab;  // set by editor

    private ComplexController[] complexControllers;
    private const float SpawnInterval = 5.0f;
    private float lastSpawn = 0.0f;

    private const int InitEnemies = 3;
    private const int IncreaseEvery = 250;

    int GetMaxEnemies() {
        return InitEnemies + GameManager.Instance.Score / IncreaseEvery;
    }

    int CountEnemies() {
        return GameObject.FindGameObjectsWithTag("EnemyTag").Length;
    }

    // Use this for initialization
    void Start () {
        complexControllers = new ComplexController[Complexes.Length];
        for (int i = 0; i < Complexes.Length; i++) {
            complexControllers[i] = Complexes[i].GetComponent<ComplexController>();
        }
    }

    // Update is called once per frame
    void Update () {
        if (GameManager.Instance.Mode != GameManager.GameMode.Playing) return;
        if (Time.time < lastSpawn + SpawnInterval) return;
        int toSpawn = GetMaxEnemies() - CountEnemies();
        while (toSpawn-- > 0) SpawnEnemy();
    }

    bool AreAllComplexesDead() {
        foreach (ComplexController c in complexControllers) {
            if (c.Alive) return false;
        }
        return true;
    }

    void SpawnEnemy() {
        // are all complexes dead? If so, give up.
        if (AreAllComplexesDead()) return;

        // what city will we strike at?
        int i = Random.Range(0, Complexes.Length);
        while (!complexControllers[i].Alive) i = (i + 1) % Complexes.Length;

        // pick a random spawn point for it
        GameObject spawnPoint = complexControllers[i].GetRandomSpawnPoint();

        // spawn it
        EnemyController.SpawnEnemy(EnemyPrefab, spawnPoint, Complexes[i]);
    }
}
